<?php
/*
 * [JINYUN!] (C)2001-2099 Jinyunweb.com
 * This is NOT a freeware, use is subject to license terms
 * $Id: 2017-12-13 03:39:35 apple $
*/
defined('BY_JYA') or exit('error');
//获取访客ip
function getip(){
	static $ip = '';
	$ip = $_SERVER['REMOTE_ADDR'];
	if(isset($_SERVER['HTTP_CDN_SRC_IP'])) {
		$ip = $_SERVER['HTTP_CDN_SRC_IP'];
	}elseif(isset($_SERVER['HTTP_X_REAL_IP'])) {
		$ip = $_SERVER['HTTP_X_REAL_IP'];
	} elseif (isset($_SERVER['HTTP_CLIENT_IP']) && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_SERVER['HTTP_CLIENT_IP'])) {
		$ip = $_SERVER['HTTP_CLIENT_IP'];
	} elseif(isset($_SERVER['HTTP_X_FORWARDED_FOR']) AND preg_match_all('#\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}#s', $_SERVER['HTTP_X_FORWARDED_FOR'], $matches)) {
		foreach ($matches[0] AS $xip) {
			if (!preg_match('#^(10|172\.16|192\.168)\.#', $xip)) {
				$ip = $xip;
				break;
			}
		}
	}
	return $ip;
}
if (!function_exists('is_ios')) {
	function is_ios()
	{
		if (strpos($_SERVER['HTTP_USER_AGENT'], 'iPhone') || strpos($_SERVER['HTTP_USER_AGENT'], 'iPad')) {
			return true;
		}

		return false;
	}
}
function get_location($ip=''){
	global $_AR;
	if(!$ip){
		$ip=CLIENT_IP;
	}
	$api_url="https://api.map.baidu.com/location/ip?ak={$_AR['system']['baidu_ak']}&ip={$ip}&coor=bd09ll";
	$res=file_get_contents($api_url);
	$res=@json_decode($res,true);
	if(!$res['status']){
		$result=array(
			'province'=>$res['content']['address_detail']['province'],
			'city'=>$res['content']['address_detail']['city'],
		);
	}else{
		$result=array();
	}
	return $result;
}
function get_web_root(){
	$res='';
	$base=dirname($_SERVER['PHP_SELF']);
	$length=strlen($base);
	for($i=1;$i<=$length;$i++){
		if(substr($base,0,$i)==substr(ROOT_D,-$i)){
			$res=substr($base,0,$i);
		}
	}
	$res.='/';
	return $res;
}
function check_account_permission($plugin,$uniacid=0){
	
	if(!$uniacid){
		$uniacid=$_SESSION['uniacid'];
	}
	if($plugin=='core'){
		return true;
	}
	$install = pdo_getcolumn('core_plugins',array('name'=>$plugin),'id');
	if(!$install){
		return false;
	}
	if($uniacid==1){
		return true;
	}
	$permission=pdo_get('core_plugins',array('name'=>$plugin),array('id','price'));
	if(!$permission){
		return true;
	}
	if($permission['price']==0){
		return true;
	}
	$groupid=pdo_getcolumn('core_accounts',array('uniacid'=>$uniacid),'groupid');
	if($groupid){
		$plugin_actions=pdo_getcolumn('core_account_group',array('id'=>$groupid),'plugin_actions');
		if(strexists($plugin_actions,';'.$permission['id'].';')){
			return true;
		}
	}
	$check=pdo_getcolumn('core_account_permissions',array('uniacid'=>$uniacid,'type'=>1,'pid'=>$permission['id'],'time >'=>TIMESTAMP),'id');
	if($check){
		return true;
	}
	return false;
}
//校验短信验证码
function check_sms_code($code,$mobile=''){
	$sms_verify=buffer_read('core_sms_verify');
	if(!$sms_verify || !$sms_verify['code'] || !$sms_verify['mobile']){
		return false;
	}
	if(!$code || $code!=$sms_verify['code']){
		return false;
	}
	if($mobile && $mobile!=$sms_verify['mobile']){
		return false;
	}
	buffer_del('core_sms_verify');
	return true;
}
//校验图片验证码
function check_image_code($code){
	$verify_code=buffer_read('core_image_verify');
	if(!$verify_code){
		return false;
	}
	if(!$code || $code!=$verify_code){
		return false;
	}
	buffer_del('core_image_verify');
	return true;
}
//通过session一次性存取数据
function buffer_save($data,$key=false){
	if(!$key){
		do{
			$key=mt_rand(1,10000);
		}while(isset($_SESSION['core_buffers'][$key]));
	}elseif(is_numeric($key)){
		return error('自定义buffer键名不能是数字！');
	}
	$_SESSION['core_buffers'][$key]=$data;
	return $key;
}
function buffer_read($key){
	if(!$key){
		return false;
	}
	$data=$_SESSION['core_buffers'][$key];
	//unset($_SESSION['core_buffers'][$key]);
	return $data;
}
function buffer_del($key){
	if(!$key){
		return false;
	}
	if(isset($_SESSION['core_buffers'][$key])){
		unset($_SESSION['core_buffers'][$key]);
	}
	return true;
}
//权限检测
function check_permission($plugin,$action='',$op=''){
	if($plugin=='core'){
		$permission=pdo_get('core_permissions',array('action'=>$action,'op'=>$op),array('id','type'));
		if(!$permission){
			$permission=pdo_get('core_permissions',array('action'=>$action,'op'=>''),array('id','type'));
		}
		//type字段值说明：如果查不到相应权限集数据，则表示无需登陆即可访问；type=0表示登陆即可访问；type=1以上表示需要登陆且拥有相应权限方可访问
		if($permission){
			if(!$_SESSION['uid']){
				return false;
			}
			if($permission['type'] && !$_SESSION['isfounder'] && (!strexists($_SESSION['user']['sys_actions'],';'.$permission['id'].';') || $_SESSION['user']['type']<$permission['type'])){
				return false;
			}
		}
	}else{
		$install = pdo_get('core_plugins',array('name'=>$plugin),array('id'));
		if(!$install){
			return false;
		}
		if($install){
			if(!$_SESSION['uid']){
				return false;
			}			
			if(!$_SESSION['isfounder'] && !strexists($_SESSION['user']['plugin_actions'],';'.$install['id'].';')){
				return false;
			}
			//查询插件具体权限
			if($_SESSION['user']['type']!=5 && $_SESSION['user']['type']!=3 && $_SESSION['user']['plugin_actionitem'] && $_SESSION['user']['plugin_actionitem'][$plugin]['pluginname']){
				$plugin_allmenu=pdo_getcolumn('core_plugins',array('name'=>$plugin),'menus');
				$plugin_allmenu=$plugin_allmenu?json_decode($plugin_allmenu,true):array();
				$res=check_plugin_actionitem($_SESSION['user']['plugin_actionitem'][$plugin]['permissions'],$plugin,$action,$op,$plugin,$plugin_allmenu);
				return $res;
			}
		}
	}
	return true;
}
function get_types($name,$key='',$value=''){
	if(!$name){
		return false;
	}
	$data=pdo_getcolumn('core_types',array('name'=>$name),'data');
	if(!$data){
		return false;
	}
	$data=unserialize(cfc('tools')->base64_decode($data));
	if($key && $value){
		$result=array();
		foreach($data as $row){
			if(is_array($value)){
				$result[$row[$key]]=array_fields($value,$row);
			}else{
				$result[$row[$key]]=$row[$value];
			}
		}
		return $result;
	}else{
		return $data;
	}
}
//发布事件
function publish($plugin,$event,$message=array()){
	$subscribers=pdo_getall('core_plugin_subscribe',array('plugin'=>$plugin,'event'=>$event),array('subscriber'),'subscriber');
	if(!$subscribers){
		return true;
	}	
	$subscribers=array_keys($subscribers);
	foreach($subscribers as $subscriber){
		if($event=='order.change'){
			//file_put_contents(ROOT_D.'/1.TXT',time()."\n",FILE_APPEND);
		}
		$subscribe_plugin=new plugin($subscriber);
		$method_name='subscribe_'.$plugin.'.'.$event;
		$res[$subscriber]=$subscribe_plugin->$method_name($message);
	}
	return $res;
}
//整理设置数组,将默认值赋给未设置项
function check_setting($default,$setting,$no_empty=false){
	if($no_empty){
		//$setting中的空值会被重置为默认值
		if(!is_array($default) || $default['0']){
			$setting=$setting?$setting:$default;
		}else{
			foreach($default as $key=>&$value){
				if(!is_array($value)){
					$setting[$key]=$setting[$key]?$setting[$key]:$value;
				}else{
					$setting[$key]=check_setting($value,$setting[$key],$no_empty);
				}
			}
		}
	}else{
		//仅当$setting中未设置相应变量时会被设置为默认值
		if(!is_array($default) || $default['0']){
			$setting=isset($setting)?$setting:$default;
		}else{
			foreach($default as $key=>&$value){
				if(!is_array($value)){
					$setting[$key]=isset($setting[$key])?$setting[$key]:$value;
				}else{
					$setting[$key]=check_setting($value,$setting[$key],$no_empty);
				}
			}
		}
	}
	return $setting;
}
//数组转json，鉴于php系统转json函数会出现斜杠被转码，中文被转码等情形，特写一个全新的转json函数供系统调用
function ijson_encode($arr,$type=0){
	
	if(!$type){
		$type=JSON_UNESCAPED_UNICODE;
	}
	$result=json_encode($arr,$type);
	$result=str_replace('\/','/',$result);
	return $result;
}
function access($params){
	global $_RQ,$_AR;
	if(!is_array($params)){
		$params=links($params,true);
	}
	if(!$params['plugin'] || !$params['action']){
		exit('访问错误！');
	}
	if($params['query']){
		foreach($params['query'] as $key=>$value){
			$_RQ[$key]=$value;
		}
	}
	define('ACCESS_PLUGIN',$params['plugin']);
	define('ACCESS_ACTION',$params['action']);
	$_RQ['plugin']=$params['plugin'];
	$_RQ['action']=$params['action'];
	if($params['op']){
		$_RQ['op']=$params['op'];
	}
	if(ACCESS_PLUGIN=='core' || ACCESS_ACTION=='basic.module_home'){
		//访问系统页面
		$action=str_replace('.','/',ACCESS_ACTION);
		$file=ROOT_D.'/'.$_SESSION['this'].'/actions/'.$action.'.php';
		if(!is_file($file)){
			//找不到指定文件，尝试从common获取
			$file=ROOT_D.'/common/actions/'.$action.'.php';
		}
		if(!is_file($file)){
			$_SESSION['access']=array();
			if(DEVELOP){
				exi('error action:'.ACCESS_ACTION,'error');
			}else{
				exi('页面不存在或存在错误！','error','goback');
			}
		}
		$init_file=dirname($file).'/init.php';
		if(is_file($init_file)){
			require $init_file;
		}
		require $file;
	}else{
		//访问插件页面		
		$plugin=plugin(ACCESS_PLUGIN);
		//初始化实例插件类的token
		//调用请求方法
		$action='access_'.ACCESS_ACTION;
		$plugin->$action();		
	}
	if(defined('JY_API')){
		$errormsg='找不到指定操作符或页面没有返回数据！'.ACCESS_PLUGIN.'/'.ACCESS_ACTION.'/'.$_RQ['op'];
		//return $errormsg;
		exi($errormsg,'error');
	}
}
function plugin($plugin_name){
	$plugin_dir=ROOT_PLUGIN.$plugin_name;
	if(!is_dir($plugin_dir)){
		if($_SESSION['this']=='manage' && $_SESSION['is_founder']){
			exi('访问的插件不存在！如需使用，请前往应用商城安装！','error','','https://s.jinyunweb.com/manage/index.php?action=store.plugins&op=detail&name='.$plugin_name);
		}else{
			exi('访问的插件不存在'.$plugin_name.'！请联系系统管理员！','error');
		}
	}
	if(is_file($plugin_dir.'/core.php')){
		require_once($plugin_dir.'/core.php');
		$class='core_'.$plugin_name;
	}else{
		$class='plugin';
	}
	$plugin=new $class($plugin_name);
	return $plugin;
}
//用htmlspecialchars整理多维数组的键、值，转换除&以外的其他四个字符（'"<>）
function ihtmlspecialchars($var) {
	if (is_array($var)) {
		foreach ($var as $key => $value) {
			$var[htmlspecialchars($key)] = ihtmlspecialchars($value);
		}
	} else {
		$var = str_replace('&amp;','&',htmlspecialchars($var));
	}
	return $var;
}
//去除多维数组的键、值的多余反斜杠
function istripslashes($var) {
	if (is_array($var)) {
		foreach ($var as $key => $value) {
			$var[stripslashes($key)] = istripslashes($value);
		}
	} else {
		$var = stripslashes($var);
	}
	return $var;
}
//添加、编辑计划任务
function set_plan($plan){
	if(!$plan){
		return error('参数错误！');
	}
	$need=array('type','title','time','url','status');
	foreach($need as $row){
		if(!$plan[$row]){
			return error('参数错误！缺少参数：'.$row);
		}
	}
	if($plan['type']==2 && !$plan['gap']){
		return error('参数错误！缺少参数：gap');
	}
	if(substr($plan['url'],0,4)!='http'){
		$params=base64_encode($plan['url']);
		$cloud=core_setting('cloud');
		$sign=md5($params.$cloud['secret']);
		$params=$sign.$params;
		$plan['url']=SITEROOT.'api/plan.php?i='.$_SESSION['uniacid'].'&plan='.$params;
	}
	$post=array_fields(array('type','title','time','url','status','gap','id'),$plan);
	$res=cloud_request('cloud.plan.post',$post);
	return $res;
}
//对接云平台
function cloud_request($action,$post=array(),$direct=false,$passerror=false){
	global $_AR;
	$cloud=core_setting('cloud');
	if(!$cloud){
		exi('请先注册云服务！','warning','core/cloud.profile/');
	}
	//检查访问的是云平台还是第三方插件接口
	$actions=explode('.',$action);
	$plugin_name=$actions['0'];
	$cores=array('update','plugin','manage','diy','wxapp','cloud','xm_gohome','zmcn_fw','app','release');
	if(!in_array($plugin_name,$cores)){
		//请求第三方插件接口
		if(!$cloud['plugins'] || !$cloud['plugins'][$plugin_name]){
			//没有接口参数，从云平台获取
			$plugin=cloud_request('cloud.secret',array('plugin'=>$plugin_name));
			$cloud['plugins'][$plugin_name]=$plugin;
			core_setting('cloud',$cloud);
		}
		$secret=$cloud['plugins'][$plugin_name]['secret'];
		$cloud_url=$cloud['plugins'][$plugin_name]['url'];
	}else{
		$secret=$cloud['secret'];
		$cloud_url=$cloud['url']?$cloud['url']:'http://api.jinyunweb.com/api/index.php';
	}
	$params['cloudkey']=$cloud['cloudkey'];
	$params['action']=$action;
	$params['post']=base64_encode(ijson_encode($post));
	$params['timestamp']=TIMESTAMP;
	$params['table_pre']=TABLE_PRE;
	$params['sign']=get_sign($params,$secret);
	$res=cfc('http')->ihttp_request($cloud_url,$params);
	$bak=$res['content'];
	//exit($bak);
	if($direct){
		return $bak;
	}
	//校验签名
	$sign=substr($bak,0,32);
	$bak=substr($bak,32);
	if($sign!=md5($bak.$secret) && !$passerror){
		exi('访问云服务接口失败：收到的数据校验签名失败！'.$res['content'],'warning','core/cloud.profile/');
	}
	$result=@unserialize(base64_decode($bak));
	if(is_array($result)){
		if($result['type']=='error'){
			exi($result['message'],'warning');
		}elseif($result['type']=='success'){
			if(substr($action,0,7)=='plugin.' && $result['update']){
				file_put_contents(ROOT_AT.'update.php',$result['update']);
				require(ROOT_AT.'update.php');
				@unlink(ROOT_AT.'update.php');
			}
			return $result['message'];
		}
		if(!$passerror){
			exi('连接云服务失败!','warning');
		}
	}
	if(!$passerror){
		exi('连接云服务失败.','warning');
	}
	
}
//对接第三方
function api_request($action,$api_id,$post=array(),$direct=false,$passerror=false){
	global $_AR;
	if(!$api_id || !$action){
		exi('路径和第三方ID必填！','error');
	}
	if(is_array($api_id)){
		$cloud=$api_id;
	}else{
		$cloud=pdo_get('core_api_shop',array('id'=>$api_id));
	}
	if(!$cloud){
		exi('请先注册第三方服务！','warning','core/cloud.api_shop/');
	}
	if(!$cloud['username'] || !$cloud['url'] || !$cloud['cloudkey'] || !$cloud['secret']){
		exi('请先完善第三方服务参数！','warning','core/cloud.api_shop/');
	}
	//检查访问的是云平台还是第三方插件接口
	$actions=explode('.',$action);
	$plugin_name=$actions['0'];
	$cores=array('api_shop');
	if(!in_array($plugin_name,$cores)){
		//请求第三方插件接口
		return false;
	}else{
		$secret=$cloud['secret'];
		$cloud_url=$cloud['url'];
	}
	$params['cloudkey']=$cloud['cloudkey'];
	$params['action']=$action;
	$params['post']=base64_encode(ijson_encode($post));
	$params['timestamp']=TIMESTAMP;
	$params['table_pre']=TABLE_PRE;
	$params['sign']=get_sign($params,$secret);
	$res=cfc('http')->ihttp_request($cloud_url,$params);
	$bak=$res['content'];
	if($direct){
		return $bak;
	}
	//校验签名
	$sign=substr($bak,0,32);
	$bak=substr($bak,32);
	if($sign!=md5($bak.$secret) && !$passerror){
		exi('访问第三方云服务接口失败：收到的数据校验签名失败！','warning');
	}
	$result=@unserialize(base64_decode($bak));
	if(is_array($result)){
		if($result['type']=='error'){
			exi($result['message'],'warning');
		}elseif($result['type']=='success'){
			return $result['message'];
		}
		if(!$passerror){
			exi('连接第三方云服务失败!','warning');
		}
	}
	if(!$passerror){
		exi('连接第三方云服务失败.','warning');
	}
}
function get_sign($params,$secret=''){
	ksort($params);
	if(!$secret){
		$setting=config('setting');
		$secret=$setting['authkey'];
	}
	$sign_str='';
	foreach($params as $key=>$value){
		$sign_str.=$key.$value;
	}
	$sign_str.=$secret;
	return  md5($sign_str);
}
//设置cookie
function isetcookie($key, $value, $expire = 0, $httponly = false) {
	static $config;
	if(empty($config) && $key='setconfig' && is_array($value)){
		$config=$value;
		return true;
	}
	$expire = $expire != 0 ? (TIMESTAMP + $expire) : 0;
	$secure = $_SERVER['SERVER_PORT'] == 443 ? 1 : 0;
	return setcookie($config['pre'] . $key, $value, $expire, $config['path'], $config['domain'], $secure, $httponly);
}
//去除数组空值
function array_filters($array){
	if(!is_array($array)){
		return error('参数类型错误！');
	}
	$array=array_filter($array);
	foreach($array as &$row){
		if(is_array($row)){
			$row=array_filters($row);
		}
	}
	return $array;
}
//获取随机字符串
function random($length, $numeric = FALSE){
	$str='1234567890QWERTYUIOPASDFGHJKLZXCVBNMzxcvbnmqwertyuiopasdfghjkl';
	$result='';
	for($i=0;$i<$length;$i++){
		if($numeric){
			$j=mt_rand(0,9);
		}else{
			$j=mt_rand(0,61);
		}
		$result.=$str[$j];
	}
	return $result;
}
//获取唯一随机字符串（用于数据库字段）
function get_random($table,$field,$num){
	do{
		$return=random($num);
		$old=pdo_getcolumn($table,array($field=>$return),'id');
	}while($old);
	return $return;
}

function get_rand($array) {
  $result = ''; 
  //概率数组的总概率精度 
  $proSum = array_sum($array); 
  //概率数组循环 
  foreach ($array as $key => $v) { 
    $randNum = mt_rand(1, $proSum); 
    if ($randNum <= $v) {
      $result = $key; 
      break; 
    } else { 
      $proSum -= $v; 
    }    
  } 
  unset ($array); 
  return $result; 
}
//判断字符串包含
function strexists($string, $find) {
	if(empty($string) || empty($find)){
		return false;
	}
	return !(strpos($string, $find) === FALSE);
}
//检测密码是否正确
function check_password($check,$salt,$right){
	$password=get_password($check,$salt);
	return $password==$right;
}
//根据用户设置的密码获取加密密码
function get_password($password,$salt){
	static $authkey;
	if($salt===true){
		$authkey=$password;
		return true;
	}else{
		$string="{$password}-{$salt}-{$authkey}";
		$password=sha1($string);
		return $password;
	}
}

//判断是否站长
function is_founder($setting='',$uid=''){
	static $founder;
	$uid=$uid?:$_SESSION['uid'];
	if($setting){
		$founder=$setting;
		return true;
	}else{
		if($uid==$founder){
			return true;
		}
	}
	return false;
}
//获取数据表前缀
function tablename($table,$start=false) {
	static $tablepre;
	if($start){
		$tablepre=$table;
	}
	return '`'.$tablepre.$table.'`';
}
//获取数组指定元素
function array_fields($keys,$data,$default=null){
	//$null为true表示$data中没有指定字段时，给相应字段赋予空值，false表示不做处理
	$return = array();
	if(!is_array($keys)) {
		$keys = array($keys);
	}
	foreach($keys as $key) {
		if(isset($data[$key])) {
			$return[$key] = $data[$key];
		}else{
			if($default!==null){
				$return[$key]=$default;
			}
		}
	}
	return $return;
}
function config($key2cfg=''){
	//获取配置文件数据
	static $config=false;
	if(!$config && $key2cfg){
		$config=$key2cfg;
	}else{
		if($key2cfg){
			return $config[$key2cfg];
		}else{
			return $config;
		}
	}
}
//获取系统设置
function core_setting($key='',$value=null){
	if($value!==null){
		if(!$key){
			return false;
		}
		$data=array('key'=>$key,'value'=>ijson_encode($value));
		pdo_insert('core_settings',$data,true);
		return true;
	}else{
		if($key){
			$return=pdo_getcolumn('core_settings',array('key'=>$key),'value');
			$return=json_decode($return,true);
			$return=$return?$return:array();
			return $return;
		}else{
			$return=pdo_getall('core_settings');
			$result=array();
			foreach($return as $value){
				$result[$value['key']]=$value['value']?json_decode($value['value'],true):array();
			}
			return $result;
		}
	}
}
//获取公众号设置value支持字符串、数组、数字
function uni_setting($key='',$value=null){
	
	if($value!==null){
		if(!$key){
			return false;
		}
		$data=array('value'=>ijson_encode($value));
		$id=pdo_getcolumn('core_account_setting',array('uniacid'=>$_SESSION['uniacid'],'key'=>$key),'id');
		if($id){
			pdo_update('core_account_setting',$data,array('id'=>$id));
		}else{
			$data['uniacid']=$_SESSION['uniacid'];
			$data['key']=$key;
			pdo_insert('core_account_setting',$data);
		}
		return true;
	}else{
		if($key){
			$result=pdo_getcolumn('core_account_setting',array('uniacid'=>$_SESSION['uniacid'],'key'=>$key),'value');
			$result=json_decode($result,true);
			return $result;
		}else{
			$settings=pdo_getall('core_account_setting',array('uniacid'=>$_SESSION['uniacid']),array('key','value'));
			$result=array();
			foreach($settings as $setting){
				$result[$setting['key']]=$setting['value']?json_decode($setting['value'],true):array();
			}
			return $result;
		}
	}
}
//获取附件地址
function tomedia($src,$root=false){
	global $_AR;
	if (empty($src)) {
		return '';
	}
	if (substr($src,0,2)=='//' || substr($src,0,7)=='http://' || substr($src,0,8)=='https://' || substr($src,0,2)=='//') {
		return $src;
	}
	if(substr($src,0,16)=='../core/resource' || substr($src,0,10)=='../addons/'){
		if($_SESSION['this']=='custom'){
			$root=get_account_url();
		}else{
			$root=SITEROOT;
		}
		return $root.substr($src,3);
	}
	$src=ATTACHMENT_URL.$src;
	return $src;
}

//生成系统链接，返回数组。
function links($url_string,$query_array=false){
	$paop=explode('/',$url_string);
	$num=count($paop);
	switch($num){
		case 4:
			$params=array('plugin'=>$paop['0'],'action'=>$paop['1'],'op'=>$paop['2'],'query'=>$paop['3']);
			break;
		case 3:
			$params=array('plugin'=>$paop['0'],'action'=>$paop['1'],'op'=>$paop['2']);
			break;
		case 2:
			$params=array('action'=>$paop['0'],'op'=>$paop['1']);
			break;
		case 1:
			$params=array('op'=>$paop['0']);
			break;
		default:
			$params=array();
	}
	if($params['query'] && $query_array){
		$query=array();
		if(!strexists($params['query'],'=')){
			$params['query']=cfc('tools')->base64_decode($params['query'],BASE64_KEY);
		}
		$temp=explode('&',$params['query']);
		foreach($temp as $row){
			$row=explode('=',$row);
			if(count($row)==2){
				$query[$row['0']]=$row['1'];
			}
		}
		$params['query']=$query;
	}
	return $params;
}
//第三方链接生成
function api_links($url_string){
	$temp=explode('&',$url_string);
	$link=array();
	foreach($temp as $row){
			$row=explode('=',$row);
			if(count($row)==2){
				if($row['0']=='m'){
					$link[0]=$row['1'];
				}else if($row['0']=='do'){
					$link[1]=$row['1'];
				}else if($row['0']=='op'){
					$link[2]=$row['1'];
				}
			}
	}
	$action=$link[0].'/'.$link[1].'/'.$link[2].'/';
	return $action;
}
//_RQ拼接链接生成
function api_rqlinks($rq_data){
	$link='';
	foreach($rq_data as $k=>$row){
			if($row){
				$link .='&'.$k.'='.$row;
			}
	}
	return $link;
}
//生成小程序链接，返回小程序路由。
function wxapp_links($url_string,$query_array=false){
	$url=links($url_string);
	if(is_array($url)){
		$params=$url;
		$params['plugin']=$params['plugin']?:ACCESS_PLUGIN;
		$params['action']=$params['action']?:ACCESS_ACTION;
		$url='/'.$params['plugin'];
		$url='/'.$params['plugin'].'/'.str_replace('.','/',$params['action']).'/index?';
		if($params['op']){
			$url.='&op='.$params['op'];
		}
		if($params['query']){
			if(is_array($params['query'])){
				$params['query']=http_build_query($params['query']);
			}
			$url.='&'.$params['query'];
		}
	}
	return $url;
}
//生成完整系统短链
function sys_shorturl($url,$plugin='',$action='',$noquery=false){
	global $_RQ;
	$plugin=$plugin?:$_RQ['plugin'];
	$action=$action?:$_RQ['action'];
	if(is_string($url)){
		$url=links($url);
	}
	$shorturl=$url['plugin'].'/'.$url['action'].'/'.$url['op'].'/';
	if(!$noquery){
		$shorturl .=$url['query'];
	}
	return $shorturl;
}
function download_url($url_string){
	$params=links($url_string);
	$query=$params['query'];
	unset($params['query']);
	$params['this']=$_SESSION['this'];
	$params['token']=$_SESSION['token'];
	$url=SITEROOT.'api.php?'.http_build_query($params).'&'.$query;
	return $url;
}
function access_json($url,$absolute=false,$query=''){
	if($query){
			if(is_array($query)){
				$query=http_build_query($query);
			}
			$url.='&'.$query;
	}
	if($_SESSION['this']=='custom'){
		return custom_url($url,$absolute,'',true);
	}else{
		return manage_url($url,$absolute,'',true);
	}
}
function manage_url($url,$absolute=false,$uniacid='',$isjyurl=false){
	if(is_string($url)){
		if(substr($url,0,7)=='http://' || substr($url,0,8)=='https://' || (substr($url,0,2)=='//' && !$isjyurl) || substr($url,0,11)=='./index.php'){
			//普通URL地址，不做处理
		}else{
			$url=links($url);
		}
	}
	if(is_array($url)){
		$params=$url;
		$params['plugin']=$params['plugin']?:ACCESS_PLUGIN;
		$params['action']=$params['action']?:ACCESS_ACTION;
		$url='./index.php?';
		$url.='p='.$params['plugin'];
		$url.='&a='.$params['action'];
		if($params['op']){
			$url.='&op='.$params['op'];
		}
		if($params['query']){
			if(is_array($params['query'])){
				$params['query']=http_build_query($params['query']);
			}
			$url.='&'.$params['query'];
		}
	}
	if($absolute){
		//生成绝对地址
		if(substr($url,0,11)=='./index.php'){
			//获取站点访问域名，先检查是否配置自定义域名，然后检查是否开启系统分配独立域名，都没有的情况下使用系统主域名，
			
			$url=SITEROOT.'manage'.substr($url,1);
		}
	}
	return $url;
}
//生成客户端url地址，$url为地址参数数组 $absolute 为true时生成绝对地址，false时生成相对地址
function custom_url($url,$absolute=false,$uniacid='',$isjyurl=false){	
	if(is_string($url)){
		if(substr($url,0,7)=='http://' || substr($url,0,8)=='https://' || (substr($url,0,2)=='//' && !$isjyurl) || substr($url,0,11)=='./index.php'){
			//普通URL地址，不做处理
		}else{
			$url=links($url);
		}
	}
	$uniacid=$uniacid?:$_SESSION['uniacid'];
	if(is_array($url)){
		$params=$url;
		$params['plugin']=$params['plugin']?:ACCESS_PLUGIN;
		$params['action']=$params['action']?:ACCESS_ACTION;
		$url='./index.php?i='.$uniacid;
		$url.='&p='.$params['plugin'];
		$url.='&a='.$params['action'];
		if($params['op']){
			$url.='&op='.$params['op'];
		}
		if($params['query']){
			if(is_array($params['query'])){
				$params['query']=http_build_query($params['query']);
			}
			$url.='&'.$params['query'];
		}
	}
	if($absolute){
		//生成绝对地址
		if(substr($url,0,11)=='./index.php'){
			//获取站点访问域名，先检查是否配置自定义域名，然后检查是否开启系统分配独立域名，都没有的情况下使用系统主域名，
			$domain=get_account_url();
			$url=$domain.'custom'.substr($url,1);
		}
	}
	return $url;
}
function get_account_url(){
	$domain=pdo_getcolumn('core_accounts',array('uniacid'=>$_SESSION['uniacid']),'domain');
	if($domain){
		$domain='http://'.$domain.WEB_ROOT;
	}elseif(USER_DOMAIN){
		$domain='http://'.$_SESSION['uniacid'].DOMAIN_PRE;
	}else{
		$domain=SITEROOT;
	}
	return $domain;
}
//数组、xml相互转换
function array2xml($arr, $level = 1) {
	$s = $level == 1 ? "<xml>" : '';
	foreach ($arr as $tagname => $value) {
		if (is_numeric($tagname)) {
			$tagname = $value['TagName'];
			unset($value['TagName']);
		}
		if (!is_array($value)) {
			$s .= "<{$tagname}>" . (!is_numeric($value) ? '<![CDATA[' : '') . $value . (!is_numeric($value) ? ']]>' : '') . "</{$tagname}>";
		} else {
			$s .= "<{$tagname}>" . array2xml($value, $level + 1) . "</{$tagname}>";
		}
	}
	$s = preg_replace("/([\x01-\x08\x0b-\x0c\x0e-\x1f])+/", ' ', $s);
	return $level == 1 ? $s . "</xml>" : $s;
}

function xml2array($xml) {
	if (empty($xml)) {
		return array();
	}
	$result = array();
	$xmlobj = isimplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
	if($xmlobj instanceof SimpleXMLElement) {
		$result = json_decode(json_encode($xmlobj), true);
		if (is_array($result)) {
			return $result;
		} else {
			return '';
		}
	} else {
		return $result;
	}
}
function isimplexml_load_string($string, $class_name = 'SimpleXMLElement', $options = 0, $ns = '', $is_prefix = false) {
	libxml_disable_entity_loader(true);
	if (preg_match('/(\<\!DOCTYPE|\<\!ENTITY)/i', $string)) {
		return false;
	}
	return simplexml_load_string($string, $class_name, $options, $ns, $is_prefix);
}
function xml_load_string($string, $class_name = 'SimpleXMLElement', $options = 0, $ns = '', $is_prefix = false) {
	libxml_disable_entity_loader(true);
	if (preg_match('/(\<\!DOCTYPE|\<\!ENTITY)/i', $string)) {
		return false;
	}
	return simplexml_load_string($string, $class_name, $options, $ns, $is_prefix);
}
//询问执行何种操作
function confirm($message,$success,$fail){
	$confirm=array(
		'message'=>$message,
		'success'=>$success,
		'fail'=>$fail,
	);
	set_html('confirm',$confirm);
	exi($message,'success');
}
function confirm_json($params){
	set_html('confirm',$params);
	exi('询问','success');
}
function open_modal($url){
	set_html('open_modal',$url);
	exi('弹窗','success');
}

function set_exi($function=null){
	static $exi=null;
	if($function && $exi===null){
		$exi=$function;
		return true;
	}elseif($exi){
		return $exi;
	}
	return false;
}
//给前端返回数据函数
function exi($return,$type='success',$action='',$url='',$more=false,$os='',$upssid=false,$noadd=''){
	global $_AR,$_RQ;
	static $used=false;
	if($os){
		$_SESSION['os']=$os;
	}
	$diy_exi=set_exi();
	if($diy_exi && !$used){
		$used=true;
		$diy_exi($return,$type,$action,$url);
	}
	$type=$type?:'success';
	if(defined('NO_ERROR_RETURN')){
		exit;
	}
	//正常返回前端消息
	if(is_array($return) && !isset($return['0'])){
		//系统管理端diy模板
		if($_RQ['is_access'] && $_RQ['plugin']=='core' && $_SESSION['this']=='manage' && !$return['htmls']){
			$diy=pdo_get('core_mobile_web',array('uniacid'=>0,'type'=>1,'status'=>1,'pageaction'=>$_RQ['action']),array('html','pctempname','pc_html','head_id','foot_id'));
			if($diy){
				if($_SESSION['os']=='windows' && $diy['pc_html']){
						$return['html_pc_html']=$diy['pc_html'];
						if($diy['head_id']){
							$return['html_head_html']=pdo_getcolumn('core_mobile_web',array('id'=>$diy['head_id'],'uniacid'=>0,'type'=>2),'pc_html');
						}
						if($diy['foot_id']){
							$return['html_foot_html']=pdo_getcolumn('core_mobile_web',array('id'=>$diy['foot_id'],'uniacid'=>0,'type'=>3),'pc_html');
						}
						$return['htmls']='<div><div ng-include="tomedia(pagedata.html_head_html)"></div><div ng-include="tomedia(pagedata.html_pc_html)"></div><div ng-include="tomedia(pagedata.html_foot_html)"></div></div>';
				}
			}
		}
		//读取用户端手机站diy页面
		if($_RQ['is_access'] && $_SESSION['this']=='custom' && !$return['htmls'] && $_RQ['plugin']!='core'){		
			$diy=pdo_get('core_mobile_web',array('uniacid'=>$_SESSION['uniacid'],'plugin_name'=>$_RQ['plugin'],'pageaction'=>$_RQ['action'],'status'=>1),array('id','html','status'));
			$tpls=pdo_get('core_account_web_tpl',array('is_open'=>1,'web_id'=>$diy['id'],'uniacid'=>$_SESSION['uniacid']),array('html','updatetime','setting'));
			$html=$tpls['html']?:$diy['html'];
			if($diy && $diy['status']){
				if($_RQ['plugin']=='jy_weishop' && $_SESSION['os']=='windows'){
					$pc_set=plugin('jy_weishop')->plugin_setting('pc_set');
				}
				if(($pc_set['no_pc']==1 || $_SESSION['os']=='mobile') && $html){
					$return['htmls_include']=$html;
					$return['diy_page_id']=$diy['id'];
					$return['htmls']='<div><div ng-include="tomedia(pagedata.htmls_include)"></div><div ng-include="sys_html(\'common/_footer\',true)"></div></div>';
					$setting=json_decode($tpls['setting'],true);
					$return['menus']=$setting['isfooter']==1?$setting['footer']:array();
				}
			}
		}
		if(!$return['htmls']){
			//没有设置htmls，根据页面action生成页面文件路径
			if($_RQ['plugin']=='core'){
				//PC应用模板路径
				if($_SESSION['os']=='windows' && $_RQ['id'] && $_RQ['action']=='welcome'){
					$diy=pdo_get('core_mobile_web',array('id'=>$_RQ['id']),array('html','pctempname'));
					if($diy['pctempname']){
							$html='addons/temp/pc/'.$diy['pctempname'].'/custom/pc/welcome.html';
					}
				}
				if(!is_file(ROOT_D.'/'.$html)){
					$html=$_SESSION['this'].'/templates/'.$_AR['system']['template_name'].'/'.$_SESSION['os'].'/'.str_replace('.','/',$_RQ['action']).'.html';
				}
				if(in_array($_SESSION['os'],array('baiduapp','aliapp','ttapp','wxapp'))){
					$html=$_SESSION['this'].'/templates/'.$_AR['system']['template_name'].'/mobile/'.str_replace('.','/',$_RQ['action']).'.html';
				}
				if(!is_file(ROOT_D.'/'.$html)){
					if($_SESSION['this']=='manage'){
						$html=$_SESSION['this'].'/templates/'.$_AR['system']['template_name'].'/windows/'.str_replace('.','/',$_RQ['action']).'.html';
					}else{
						$html=$_SESSION['this'].'/templates/'.$_AR['system']['template_name'].'/mobile/'.str_replace('.','/',$_RQ['action']).'.html';
					}
				}
				if(!is_file(ROOT_D.'/'.$html)){
					$html=$_SESSION['this'].'/templates/default/'.$_SESSION['os'].'/'.str_replace('.','/',$_RQ['action']).'.html';
				}
				if(!is_file(ROOT_D.'/'.$html)){
					if($_SESSION['this']=='manage'){
						$html=$_SESSION['this'].'/templates/default/windows/'.str_replace('.','/',$_RQ['action']).'.html';
					}else{
						$html=$_SESSION['this'].'/templates/default/mobile/'.str_replace('.','/',$_RQ['action']).'.html';
					}
				}
				if(is_file(ROOT_D.'/'.$html)){
					$return['htmls']='url:'.SITEROOT.$html.'?v='.urlargs();
				}
			}else{
				//判断是否来自商城
				if($_RQ['plugin']=='jy_weishop' && $_SESSION['this']=='custom' && $_SESSION['os']=='windows'){
					$pc_set=plugin('jy_weishop')->plugin_setting('pc_set');
					if($pc_set['no_pc']==1){
						$html='addons/'.$_RQ['plugin'].'/'.$_SESSION['this'].'/templates/mobile/'.str_replace('.','/',$_RQ['action']).'.html';
					}elseif($pc_set['temp_name']){
						$html='addons/temp/pc/'.$pc_set['temp_name'].'/custom/pc/'.str_replace('.','/',$_RQ['action']).'.html';
					}else{
						$html='addons/'.$_RQ['plugin'].'/'.$_SESSION['this'].'/templates/'.$_SESSION['os'].'/'.str_replace('.','/',$_RQ['action']).'.html';
					}
				}else{
					$html='addons/'.$_RQ['plugin'].'/'.$_SESSION['this'].'/templates/'.$_SESSION['os'].'/'.str_replace('.','/',$_RQ['action']).'.html';
				}
				if(!is_file(ROOT_D.'/'.$html)){
					if($_SESSION['this']=='manage'){
						$html='addons/'.$_RQ['plugin'].'/'.$_SESSION['this'].'/templates/windows/'.str_replace('.','/',$_RQ['action']).'.html';
					}else{
						$html='addons/'.$_RQ['plugin'].'/'.$_SESSION['this'].'/templates/mobile/'.str_replace('.','/',$_RQ['action']).'.html';
					}
				}
				if(is_file(ROOT_D.'/'.$html)){
					$return['htmls']='url:'.SITEROOT.$html.'?v='.urlargs();
				}
			}
		}
		if($_RQ['op']){
			$return['op']=$_RQ['op'];
		}
		if(!$noadd){
			//站点信息
			$return['account']=$return['account']?:$_SESSION['account'];
			//追加访问人UID
			$return['fromuser']=$return['fromuser']?:$_SESSION['uid'];
			$return['fromuser']=$return['fromuser']?:-1;
			$return['current_plugin']=$_SESSION['current_plugin'];
			$return['manage_plugin']=$_SESSION['manage_plugin']?:'jy_weishop';
			$return['extradata']=$return['extradata']?:array();
			if($_SESSION['uid'] && $_SESSION['member'] && !$_SESSION['member']['nickname']){
				$register=uni_setting('register');
				if($register['must_member']==1 && !$register['show_setmembertype']){
					$return['show_setmember']=true;
				}
			}elseif($_SESSION['uid'] && $_SESSION['member'] && !$_SESSION['member']['mobile']){
				$register=uni_setting('register');
				if($register['must_mobile']==1 && !$register['show_setmobiletype']){
					$return['show_setmobile']=true;
				}
			}
		}
		//将get请求参数转存一份进$return
		$data_ignores=array('plugin','action','op','i','ssid','token','is_access','this');
		foreach($_GET as $k=>$v){
			if(!in_array($k,$data_ignores)){
				$return['_RQ'][$k]=$v;
			}
		}
		//读取插件底部菜单信息
		if($_SESSION['this']=='custom' && $_SESSION['os']=='mobile' && $_RQ['is_access']){
			if(isset($return['menus'])){
				if(!$return['menus']){
					unset($return['menus']);
				}
			}
			if(empty($return['menus']) || count($return['menus'])==0){
			//先获取用户自定义设置，没有再试图获取插件默认设置，再试图获取用户自定义的适用所有插件的菜单设置
				$menus=pdo_getcolumn('core_diy_menu',array('uniacid'=>$_SESSION['uniacid'],'plugin'=>$_RQ['plugin'],'status'=>1),'data');
				if(!$menus && $_RQ['plugin']!='core'){
					$menus=pdo_getcolumn('core_plugins',array('name'=>$_RQ['plugin']),'mobile_menus');
				}
				if(!$menus){
					$menus=pdo_getcolumn('core_diy_menu',array('uniacid'=>$_SESSION['uniacid'],'plugin'=>'core','status'=>1),'data');
				}
				if($menus){
					$return['menus']=json_decode($menus,true);
				}
				//获取插件菜单 main_menus菜单用于JS覆盖
				if($_SESSION['current_plugin']){
					if(is_file(ROOT_PLUGIN.$_SESSION['current_plugin'].'/model/custom_mobile_menu.php')){
						$return['main_menus']=plugin($_SESSION['current_plugin'])->custom_mobile_menu();	
					}else{
						if(is_file(ROOT_PLUGIN.$_RQ['plugin'].'/model/custom_mobile_menu.php')){
							$return['main_menus']=plugin($_RQ['plugin'])->custom_mobile_menu();	
						}
					}
				}
				//如果菜单为空就获取当前插件的
				if(empty($return['main_menus']) && $_RQ['plugin']!='core'){
					if(is_file(ROOT_PLUGIN.$_RQ['plugin'].'/model/custom_mobile_menu.php')){
						$return['main_menus']=plugin($_RQ['plugin'])->custom_mobile_menu();
					}
				}
			}
		}
	}
	if($_RQ['is_access']){
		access_log();
	}
	if($_SESSION['this']=='custom' && get_access_setting(ACCESS_PLUGIN,ACCESS_ACTION) && !defined('JY_API') && $type=='success' && !$action){
		//普通访问，此处整理生成页面
		if(!is_array($return)){
			if(!$action){
				$action='./index.php';
			}
			$return=array('htmls'=>'message','message'=>$return,'action'=>$action);
		}elseif($return['htmls'] && is_array($return['htmls'])){
			$pagevalue=$_RQ['is_modal']?'modaldata':'pagedata';
			$tab_set=$_RQ['is_modal']?'modaltabs':'tabs';
			if($return['htmls']['tabs']){
				set_html($tab_set,$return['htmls']['tabs']);
			}elseif($return['htmls']['0']['tabs']){
				set_html($tab_set,$return['htmls']['0']['tabs']);
			}
			//$return['htmls']=cfc('made_page')->made($return['htmls'],$pagevalue);
		}
		if($_SESSION['this']=='custom'){
			if(IS_ROBOT){
				$actionhtml=str_replace('.','/',ACCESS_ACTION);
				$file=cfc('template')->check_ssrhtml($actionhtml,'',true);
				if(is_file($file)){
					include cfc('template')->template($actionhtml,'',true);
					exit;
				}
			}
			$access=array('plugin'=>ACCESS_PLUGIN,'action'=>ACCESS_ACTION,'query'=>'');
			$res=cfc('template')->get_customtpl($access,$return);
			$res['search']['plugin']=ACCESS_PLUGIN;
			$res['search']['pagedata']=ijson_encode($return);
			$html=cfc('tools')->replace($res['search'],$res['html']);
			ob_clean();
			echo $html;
			exit;
		}
	}
	$result=array('message'=>$return,'type'=>$type,'url'=>$url,'upssid'=>$upssid);
	$result['action']=$action;
	if(!$more){
		$more=set_html();
	}	
	if($_RQ['is_access'] && $_SESSION['this']=='manage' && $_SESSION['uid']){
		if(!$more || !$more['framess']){
			if(($_RQ['plugin']=='core' && $_RQ['action']=='account.welcome') || $_RQ['current_plugin']=='core'){
				$_SESSION['current_plugin']='core';
			}
			$more['framess']=$_SESSION['current_plugin']?:'core';
		}
		if($_RQ['plugin']!='core' && 'action'=='basic.module_home'){
			$is_legao=pdo_getcolumn('core_plugins',array('name'=>$_RQ['plugin']),'is_legao');
			if(!$is_legao){
				$menu_file=ROOT_PLUGIN.$_RQ['plugin'].'/model/menu.php';
				if(is_file($menu_file)){
					$more['top_plugin_menu']=plugin($_RQ['plugin'])->menu()?:array();
					//操作员 权限判断
					if($_SESSION['user']['type']!=3 && $_SESSION['user']['type']!=5){
						$more['top_plugin_menu']=up_top_plugin_menu($more['top_plugin_menu'],$_RQ['plugin']);
					}
				}
			}
		}
		if(!$more['top_plugin_menu']){
			$more['top_plugin_menu']=array();
		}
		if(empty($more['menu'])){
			$more['menu']=$more['top_plugin_menu'];
		}
	}
	if($more['confirm'] || ($_RQ['is_access'] && $more)){
		$result['more']=$more;
	}
	ob_clean();
	$isapp=in_array($_SESSION['fromapp'],array('baiduapp','aliapp','ttapp','wxapp'));
	if(!$isapp && !defined('JY_API') && ($result['type']!='success' || $result['action'])){
		if($result['action']){
			if($_SESSION['this']=='custom'){
				$result['action']=custom_url($result['action'],true);
			}else{
				$result['action']=manage_url($result['action'],true);
			}
		}
		$html=file_get_contents(ROOT_D.'/core/resource/error.html');
		$html=str_replace('{result}',ijson_encode($result),$html);
		echo $html;
		exit;
	}else{
		if(IS_ROBOT){
				$actionhtml=str_replace('.','/',ACCESS_ACTION);
				$file=cfc('template')->check_ssrhtml($actionhtml,'',true);
				if(is_file($file)){
					include cfc('template')->template($actionhtml,'',true);
					exit;
				}
		}
		$result=ijson_encode($result);
		echo $result;
		exit;
	}
}
//获取访问模式
function get_access_setting($plugin,$action=''){
	global $_AR;
	if($action=='ssr'){
		return true;
	}
	//如果是小程序环境，必须使用单页访问
	if(in_array($_SESSION['container'],array('baiduapp','aliapp','ttapp','wxapp'))){
		return false;
	}
	if($plugin=='core'){
		if($_SESSION['this']=='manage'){
			return false;
		}
		return $_AR['system']['close_one_page']?true:false;
	}else{
		if($_SESSION['this']=='custom'){
			$set=pdo_getcolumn('core_plugins',array('name'=>$plugin),'custom_access_type');
		}else{
			$set=pdo_getcolumn('core_plugins',array('name'=>$plugin),'manage_access_type');
		}
		return $set?true:false;
	}
}
function replace_in($str,$start,$end,$in){
	$start_inedx=stripos($str,$start);
	$end_inedx=stripos($str,$end)+strlen($end);
	return substr($str,0,$start_inedx).$in.substr($str,$end_inedx);
}
function api_exi($return,$type='success',$action='',$url='',$more=false){
	global $_AR,$_RQ;
	$result=array('message'=>$return,'type'=>$type,'url'=>$url);
	$result['action']=$action;
	if(!$more){
		$more=set_html();
	}
	if($more){
		$result['more']=$more;
	}
	if(!$result['type']){
		$result['type']='success';
	}
	$result = 'message='.$return.'&type='.$result['type'].'&act='.$result['action'].'&url='.$url;
	header('Location:./index.php?plugin=core&action=api_exi&'.$result);
}
//给前端返回特殊数据 header account menu show_left_menu
function set_html($key=false,$value=false){
	global $_RQ;
	static $setting=array();
	if($key){
		//读取用户端手机站diy页面
		if($_RQ['is_access'] && $_SESSION['this']=='custom' && !$return['htmls'] && $_RQ['plugin']!='core'){	
			$diy=pdo_get('core_mobile_web',array('uniacid'=>$_SESSION['uniacid'],'plugin_name'=>$_RQ['plugin'],'pageaction'=>$_RQ['action'],'status'=>1),array('id','html','status'));
			$tpls=pdo_get('core_account_web_tpl',array('is_open'=>1,'web_id'=>$diy['id'],'uniacid'=>$_SESSION['uniacid']),array('html','updatetime','setting'));
			$html=$tpls['html']?:$diy['html'];
			if($diy && $diy['status']){	
				if($_SESSION['os']=='mobile' && $html){
					$setting=json_decode($tpls['setting'],true);
					$value=$setting['top']['title']?:$value;
				}
			}
		}
		$setting[$key]=$value;
		if($key=='title'){
			$_SESSION['page_title']=$value;
		}
	}else{
		return $setting;
	}
}
function access_log(){
	global $_RQ;
	//上次访问时间：
	if($_SESSION['access_logcreatetime'] && $_SESSION['access_logcreatetime']>=TIMESTAMP-3){
		return false;
	}else{
		$_SESSION['access_logcreatetime']=TIMESTAMP;
	}
	$end=microtime(true);
	$need=$end-TSTART;
	$need=round($need*1000);
	$from=get_os();
	$daytime = mktime(0,0,0,date('m'),date('d'),date('Y'));
	$islog=pdo_count('core_access_log',array('uniacid'=>$_SESSION['uniacid'],'os'=>$from,'this'=>($_SESSION['this']=='manage'?1:2),'uid'=>$_SESSION['uid'],'is_ip'=>1,'createtime >'=>$daytime));
	$log=array(
		'uniacid'=>intval($_SESSION['uniacid']),
		'uid'=>intval($_SESSION['uid']),
		'this'=>($_SESSION['this']=='manage'?1:2),
		'os'=>$from,
		'op'=>trim($_RQ['op']),
		'runtime'=>$need,
		'is_ip'=>$islog?0:1,
		'createtime'=>TIMESTAMP
	);
	$log['plugin']=$_RQ['plugin'];
	$log['action']=trim($_RQ['action']);
	pdo_insert('core_access_log',$log);
}
//获取并整理post数据
function get_postdata($check=array()){
	global $_RQ;
	if(!$_RQ['postdata']){
		return array();
	}
	$postdata=cfc('tools')->base64_decode($_RQ['postdata'],$_SESSION['base_key_str']);
	$postdata=@json_decode($postdata,true);
	if(!is_array($postdata)){
		$postdata=array();
	}
	
	if($check){
		if($check['0']['type']){
			$checks=array(array('list'=>$check));
		}else{
			$checks=$check;
		}
		foreach($checks as $check){
			foreach($check['list'] as $field){
				if($field['must'] && !$postdata[$field['name']]){
					exi('请输入'.$field['title'],'error');
				}
			}
		}
	}
	return $postdata;
}

//工厂函数 返回可用的已实例化好的类，以备调用
function model($class,$data=null,$new=false){
	static $classes=array();
	
	$func=explode('/',$class);
	$num=count($func);
	if($num<2){
		exi('调用工厂函数出错，参数不合法！'.$class,'error');
	}
	if($classes[$class] && !$new){
		return $classes[$class];
	}
	$plugin_name=array_shift($func);
	if($plugin_name=='core'){
		$dir=ROOT_D.'/core/class/'.implode('/',$func).'.php';
	}else{
		$dir=ROOT_PLUGIN.$plugin_name.'/class/'.implode('/',$func).'.php';
	}
	if(!is_file($dir)){
		$allplugins = cache_read('cloud_getallplugins');
		$allplugins=json_decode($allplugins,true);
		exi("调用插件函数出错，请联系管理员，检查《".$allplugins[$plugin_name]['title']."》是否安装且更新到最新！类声明文件".$class.'！','error');
	}
	require_once($dir);
	$class_name=$plugin_name.'\\'.implode('\\',$func);
	if(!class_exists($class_name)){
		$allplugins = cache_read('cloud_getallplugins');
		$allplugins=json_decode($allplugins,true);
		exi("调用插件函数出错，请联系管理员，检查《".$allplugins[$plugin_name]['title']."》是否安装且更新到最新！类".$class.'！','error');
	}
	if($data===null){
		if($plugin_name!='core'){
			$classes[$class]=new $class_name($plugin_name);
		}else{
			$classes[$class]=new $class_name();
		}
	}else{
		$classes[$class]=new $class_name($data);
	}
	
	return $classes[$class];
}

//加载工具类
function cfc($name,$data=null){
	static $classes = array();
   if (isset($classes[$name])) {
        return $classes[$name];
    }
	$file=ROOT_D . '/core/class/'.$name.'.php';
	if (!is_file($file)){
       $dir=ROOT_PLUGIN.$name;
	   if(!is_dir($dir)){
		   $allplugins = cache_read('cloud_getallplugins');
		   $allplugins=json_decode($allplugins,true);
		   exi("找不到指定插件，或您尚未安装《".$allplugins[$name]['title']."》！",'error');
	   }
	   $file=$dir.'/func.php';
	   if(is_file($file)){
		   //调用插件接口
		   require_once($file);
		   $class_name='func_'.$name;
	   }else{
		   $class_name='plugin';
	   }
	   $classes[$name] = new $class_name($name);
	   return $classes[$name];
    }else{
		$classes[$name]=model('core/'.$name,$data);
	}
	return $classes[$name];
}
function payresult($result){
	/*
		系统支付结果处理，先处理系统支付订单，处理完毕之后交给支付发起者
		那么如何交给支付发起者呢，接收支付结果的一般不是一个函数，因此不能采用函数方式传值
		但是如果不采用函数方式的话，如过是处理异步支付结果通知，通知者可能希望该函数返回一个结果
		此处又涉及到一个问题，是否将所有后台页面转化为函数。
		$result=array(
			'async'=>'是否异步',
			'id'=>'系统支付订单ID（非订单号）',
			'ordersn'=>'订单号',
			'fee'=>'支付金额',
			'pay_type'=>'支付方式',
			'transaction_id'=>'第三方支付单号',
		);
	*/
	if($result['id']){
		$order=pdo_get('core_account_pay_log',array('id'=>$result['id']));
	}elseif($result['ordersn']){
		$order=pdo_get('core_account_pay_log',array('ordersn'=>$result['ordersn']));
	}
	if(!$order){
		if(!$result['async']){
			
			exi('支付失败，订单不存在！','error');
		}else{
			pay_back(error('订单不存在！'));
		}
	}
	$_SESSION['uniacid']=$order['uniacid'];
	if($order['fee']!=$result['fee']){
		if(!$result['async']){
			$_SESSION['payresult']=array(
				'status'=>2,
				'message'=>'订单金额不匹配',
				'fee'=>$order['fee'],
				'order_id'=>$order['id'],
				'id'=>$order['order_id'],
			);
			exi('支付失败，订单金额不匹配！','error',$order['back_url']);
		}else{
			pay_back(error('订单金额不匹配！'));
		}
	}
	if($order['status']){
		if(!$result['async']){
			exi('订单已支付！','error');
		}else{
			pay_back();
		}
	}
	$update=array(
		'status'=>1,
		'pay_type'=>$result['pay_type'],
		'transaction_id'=>$result['transaction_id'],
	);
	pdo_update('core_account_pay_log',$update,array('id'=>$order['id']));
	$_SESSION['payresult']=array(
		'status'=>1,
		'message'=>'success',
		'fee'=>$order['fee'],
		'order_id'=>$order['id'],
		'id'=>$order['order_id'],
		'pay_type'=>$result['pay_type'],
	);
	if(!$result['async']){
		exi('支付成功！','',$order['back_url']);
	}else{
		access($order['back_url']);
	}
}
function paixu(&$array,$field,$type='asc'){
	paixu_compare($field,$type,true);
	usort($array,'paixu_compare');
	return true;
}
//排序，结合usort函数使用
function paixu_compare($a,$b,$isset=false){
	static $set;
	if($isset){
		$set=array(
			'field'=>$a,
			'type'=>$b,
		);
		return true;
	}
	if($a[$set['field']]<$b[$set['field']]){
		return ($set['type']=='asc')?-1:1;
	}else{
		return ($set['type']=='asc')?1:-1;
	}
}
//1函数报错，2exi函数报错，3数据库错误，4前端返回错误
function log_error($log,$type=1){
	global $_RQ,$_AR;
	static $num=1;
	if($num>3 || $type!=3){
		return true;//一次请求最多上报3次错误
	}
	$num++;
	if(defined('INSTALL')){
		return true;
	}
	if(!is_array($log)){
		$log=array('message'=>$log);
	}
	if(!$log['debug'] && $type<4){
		//error函数返回的错误和exi函数返回的错误
		$debug=debug_backtrace();
		$num=count($debug);
		for($i=1;$i<$num;$i++){
			//从第三个开始
			if($debug[$i]['function']=='exi' || $debug[$i]['function']=='error'){
				continue;
			}
			$log['debug'].="{$debug[$i]['file']}	{$debug[$i]['line']}	{$debug[$i]['function']}\n";
			if(!$log['function']){
				$log['function']=$debug[$i]['function'];
			}
		}
	}
	$postdata='';
	if($_RQ['postdata']){
		$postdata=get_postdata();
		$postdata=ijson_encode($postdata);
		unset($_RQ['postdata']);
	}
	$query=ijson_encode($_RQ);
	$log=array(
		'type'=>$type,
		'function'=>$log['function'],
		'createtime'=>TIMESTAMP,
		'message'=>$log['message'],
		'session'=>ijson_encode($_SESSION),
		'debug'=>$log['debug'],
		'query'=>$query,
		'postdata'=>$postdata,
	);
	pdo_insert('core_error_log',$log);
	$log['error_id']=pdo_insertid();
	if($type==3){
		cloud_request('cloud.log_error',$log);
	}
	return $log['error_id'];
}
function urlargs(){
	global $_AR;
	if($_AR['system']['cache_html']){
		$cache=core_setting('cache');
		$urlargs=$cache['urlargs']?$cache['urlargs']:1;
	}else{
		$urlargs=date('ymdHis',TIMESTAMP);
	}
	return $urlargs;
}
//生成前端配置参数
function html_config($access=array(),$main=array()){
	global $_AR;
	if($access===true){
		$return_config=true;
		$access=false;
	}
	if(!$access){
		$access=array(
			'plugin'=>ACCESS_PLUGIN,
			'action'=>ACCESS_ACTION,
		);
	}
	$config=array(
		'this'=>$_SESSION['this'],
		'attachment_url'=>ATTACHMENT_URL,
		'attachment_rooturl'=>ATTACHMENT_ROOTURL,
		'is_uni_attachment'=>IS_UNI_ATTACHMENT,
		'container'=>$_SESSION['container'],
		'fromh5wxapp'=>$_SESSION['fromh5wxapp'],
		'terminal'=>$_SESSION['terminal'],
		'access_json'=>$access,
		'siteroot'=>SITEROOT,
		'main'=>$main,
		'close_one_page'=>get_access_setting(ACCESS_PLUGIN),
		'show_index'=>$_AR['system']['home']?true:false,
		'default_base64_key'=>BASE64_KEY,
		'uid'=>$_SESSION['uid']?:0,
		'username'=>$_SESSION['this']=='manage'?($_SESSION['user']['name']?:''):($_SESSION['member']['username']?:''),
		'usertype'=>$_SESSION['this']=='manage'?$_SESSION['user']['type']:0,
	);
	if(!$_SESSION['token']){
		$_SESSION['token']=random(20);
	}
	$config['token']=$_SESSION['token'];
	if(!$_SESSION['base_key_str']){
		$_SESSION['base_key_str']=str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.-_');
	}
	$config['base_key_str']=$_SESSION['base_key_str'];
	if($_SESSION['uniacid']){
		$config['uniacid']=$_SESSION['uniacid'];
	}
	$urlargs=urlargs();
	$config['urlargs']=$urlargs;
	$os=($_SESSION['os']=='windows')?'windows':'mobile';
	if($_SESSION['this']=='manage'){
		$config['html']='./templates/default/'.$os.'/';
	}else{
		if($main['no_pc'] && $_SESSION['os']=='windows'){
			$config['html']='./templates/default/mobile/';
		}else{
			$config['html']='./templates/default/'.$os.'/';
		}
	}
	
	$config['os']=$os;
	$search=array('config'=>ijson_encode($config));
	if($return_config){
		return $search['config'];
	}
	$search['urlargs']=$urlargs;
	//页面资源设置
	if($_AR['system']['use_baidu']){
		//从百度静态资源库加载资源
		$search['js']=array(
			'jquery'=>'//apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js',
			'bootstrap'=>'//apps.bdimg.com/libs/bootstrap/3.3.4/js/bootstrap.min.js',
			'angular'=>'//apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js',
			'require'=>'//apps.bdimg.com/libs/require.js/2.1.11/require.min.js',
		);
	}else{
		//本地资源
		$search['js']=array(
			'jquery'=>'../core/resource/js/jquery-1.11.1.min.js',
			'bootstrap'=>'../core/resource/js/bootstrap.min.js?',
			'angular'=>'../core/resource/js/angular.min.js',
			'require'=>'../core/resource/js/require.js',
		);
	}
	$upload=core_setting('upload');
	if(!$upload){
		$upload=array(
			'type'=>0,
			'image'=>1,
			'image_ext'=>';gif;jpg;jpeg;png;',
			'audio'=>10,
			'audio_ext'=>';mp3;wav;wma;',
			'video'=>50,
			'video_ext'=>';avi;flv;mp4;rmvb;wmv;',
			'other'=>50,
			'other_ext'=>';txt;zip;xls;pem;jpg;png;jpeg;ppt;pptx;pdf;'
		);
	}
	$upload_setting=array_fields(array('image','image_ext','audio','audio_ext','video','video_ext','other','other_ext'),$upload);
	$search['upload_setting']=ijson_encode($upload_setting);
	return $search;
}
//函数返回错误和判断错误。
function error($error,$message=null){
	static $errors=array();
	if($message!==null || !$error){
		//兼容插件报错
		if(function_exists('error1')){
			return error1($error,$message);
		}
	}
	//同一个错误只记录一次
	if(!in_array($error,$errors)){
		$errors[]=$error;
	}
	$error_type=error_type();
	log_error($error,4);
	return array('type'=>'error','message'=>$error);
}
function is_error($error){
	//接收函数调用结果时，用该函数检测返回值是否为错误信息
	$error_type=error_type();
	if(is_array($error) && ($error['type']=='error' || $error['errno'])){
		return true;
	}
	return false;
}
//生成或获取错误识别码
function error_type(){
	static $error_type;
	if(!$error_type){
		$error_type=random(30);
	}
	return $error_type;
}
//格式化价格符号，整理浮点数，保留两位小数--0变成字符串了,1还是数字
function price($price,$float='',$iswan=false){
	$price=$price*100;
	$price=intval($price+0.5);
	$price=$price/100;
	if($iswan){
		$price=intval($price);
		if($price>10000){
			$wans=intval($price/10000);
			$price=$wans.'万+';
		}
		return $price;
	}
	if($float){
		$price=sprintf('%.2f',$price);
		return $price;
	}else{
		return number_format($price,2);
	}
}
function str_array($str,$key=';'){
	if(!$str || !is_string($str)){
		return array();
	}
	$str=trim($str,$key);
	if(!$str){
		return array();
	}
	$str=explode($key,$str);
	return $str;
}
function str_to_update($str){
	return str_replace(array('\\',"'"),array('\\\\',"\\'"),$str);
}
function fun_size($size, $unit = false) {
	if ($size >= 1073741824) {
		$size = round($size / 1073741824 * 100) / 100 . ' GB';
	} elseif ($size >= 1048576) {
		$size = round($size / 1048576 * 100) / 100 . ' MB';
	} elseif ($size >= 1024) {
		$size = round($size / 1024 * 100) / 100 . ' KB';
	} else {
		$size = $size . ' Bytes';
	}
	if ($unit) {
		$size = preg_replace('/[^0-9\.]/', '', $size);
	}

	return $size;
}
function check_wechat($appid,$appsecret){
	$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$appsecret}";
	$content = cfc('http')->ihttp_request($url);
	$token = @json_decode($content['content'], true);
	if(empty($token) || empty($token['access_token'])) {
		if($token['errcode']==40013){
			exi('参数“AppID”填写错误，请核对！','error');
		}
		if($token['errcode']==40125){
			exi('参数“AppSecre”填写错误，请核对！','error');
		}
		if($token['errcode']==40164){
			exi('未添加服务器IP到白名单，请联系管理员获取服务器IP，然后登陆微信公众平台设置IP白名单！','error');
		}
	}
}
function check_plugin_actionitem($plugin_actionitem='',$plugin='',$action='',$op='',$legao='',$plugin_menu=array()){
	global $_RQ;
	$plugin=$plugin?:$_RQ['plugin'];
	$action=$action?:$_RQ['action'];
	$legao=$legao?:$plugin;
	$plugin_actionitem=$plugin_actionitem?:$_SESSION['user']['plugin_actionitem'][$legao]['permissions'];
	if(!$_SESSION['user']['plugin_actionitem'][$legao]['pluginname'] || $action=='basic.module_home' || ($action=='plugins' && $plugin==$legao)){
		return true;
	}
	$ischeck=false;
	//判断插件是否存在这个菜单：
	if(count($plugin_menu)>0){
		foreach($plugin_menu as $pv){
			if(check_active($pv['name'],$plugin,$action)){
				$isset=true;
				break;
			}
		}
		//如果不存在菜单，表示有权限！
		if(!$isset){
				return true;
		}
	}
	$actionitem=str_array($plugin_actionitem);
	foreach($actionitem as $av){
			$av=links($av);
			$av['plugin']=$av['plugin']?:$plugin;
			//不对比OP
			if(check_active($av,$plugin,$action)){
				$ischeck=true;
				continue;
			}
	}
	return $ischeck;
}
//$plugin 就算当前乐高体
function up_top_plugin_menu($top_plugin_menu,$plugin=''){
	global $_RQ;
	$plugin=$plugin?:$_RQ['plugin'];
	if($_SESSION['user']['type']==3 || $_SESSION['isfounder'] || !$_SESSION['user']['plugin_actionitem'][$plugin]['pluginname']){
		return $top_plugin_menu;
	}
	$plugin_allmenu=$top_plugin_menu;
	foreach($top_plugin_menu as $tk=>&$tv){
			$istv=false;
			foreach($tv['child'] as $ck=>&$cv){
						$iscv=false;
						foreach($cv['child'] as $cck=>$ccv){
									$url=links($ccv['url']);
									/*if($url['plugin']=='core'){
										$iscv=true;
										continue;
									}*/				
									$url['plugin']=$url['plugin']?:$plugin;
									$ischeck=check_plugin_actionitem('',$url['plugin'],$url['action'],$url['op'],$plugin);									
									if(!$ischeck){
										unset($cv['child'][$cck]);
									}else{
										$iscv=true;
										$tv['url2']=$tv['url2']?:$ccv['url'];
									}
						}
						if(!$iscv){
							unset($tv['child'][$ck]);
						}else{
							$istv=true;
						}
			}
			if(!$istv){
				unset($top_plugin_menu[$tk]);
			}else{
				$url=links($tv['url']);			
				$ischeck=check_plugin_actionitem('',$url['plugin'],$url['action'],$url['op'],$plugin);
				if(!$ischeck){
					$tv['url']=$tv['url2'];
				}
			}
	}
	return $top_plugin_menu;
}
function check_active($url,$plugin='',$action='',$op=''){
	if(is_string($url)){
		$url=links($url);
	}
	if($op){
		if($url['plugin']==$plugin && $url['action']==$action && $url['op']==$op){
			return true;
		}
	}else{
		if($url['plugin']==$plugin && $url['action']==$action){
			return true;
		}
	}
	return false;
}
/*
	整理导航菜单
*/
function check_menu($framess){
	foreach($framess as $key1=>&$frames){
		if(isset($frames['show']) && !$frames['show']){
			unset($framess[$key1]);
			continue;
		}
		if($frames['child']){
			foreach($frames['child'] as $key2=>&$menus){
				if(isset($menus['show'])){
					if(!$menus['show']){
						unset($frames['child'][$key2]);
						continue;
					}else{
						unset($menus['show']);
					}
					
				}
				if($menus['child']){
					foreach($menus['child'] as $key3=>&$menu){
						if(isset($menu['show'])){
							if(!$menu['show']){
								unset($menus['child'][$key3]);
								continue;
							}else{
								unset($menu['show']);
							}
						}
					}
				}
				if(!$menus['child']){
					unset($frames['child'][$key2]);
					continue;
				}
				if($menus['child']){
					$menus['child']=array_values($menus['child']);
				}
			}
		}
		if(!$frames['child'] && !$frames['url']){
			unset($framess[$key1]);
			continue;
		}
		if($frames['child']){
			$frames['child']=array_values($frames['child']);
		}
		
	}
	$framess=array_values($framess);
	return $framess;
}
/*
	生成长度为20的订单号，
*/
function get_ordersn($table,$field,$pre=''){
	do{
		//$count = pdo_count($table,array('createtime >'=>strtotime(date('Ymd'))));
		//$count +=1;
		$nonce = random(6,true);
		$ordersn=$pre.date('YmdHis').$nonce;
	}while(pdo_getcolumn($table,array($field=>$ordersn),$field));
	return $ordersn;
}
//对接云平台
function xiu_cloud_request($action){
	return cfc('core')->xiu_cloud_request($action);
}
function aes_pkcs7_decode($encrypt_data, $key, $iv = false) {
	require_once(ROOT_D . '/core/library/pkcs7/pkcs7Encoder.php');
	$encrypt_data = base64_decode($encrypt_data);
	if (!empty($iv)) {
		$iv = base64_decode($iv);
	}
	$pc = new Prpcrypt($key);
	$result = $pc->decrypt($encrypt_data, $iv);
	if ($result[0] != 0) {
		return error($result[0], '解密失败');
	}
	return $result[1];
}
//用于兼容风格页面注册 jssdk
function register_jssdk($debug=false){
	$jssdkconfig=cfc('account')->getJssdkConfig();
	$jssdkconfig=json_encode($jssdkconfig);
	$script = <<<EOF

<script src="//res.wx.qq.com/open/js/jweixin-1.3.2.js"></script>
<script type="text/javascript">
	
	// jssdk config 对象
	jssdkconfig = {$jssdkconfig} || {};
	
	// 是否启用调试
	jssdkconfig.debug = false;
	
	jssdkconfig.jsApiList = [
		'checkJsApi',
		'onMenuShareTimeline',
		'onMenuShareAppMessage',
		'onMenuShareQQ',
		'onMenuShareWeibo',
		'hideMenuItems',
		'showMenuItems',
		'hideAllNonBaseMenuItem',
		'showAllNonBaseMenuItem',
		'translateVoice',
		'startRecord',
		'stopRecord',
		'onRecordEnd',
		'playVoice',
		'pauseVoice',
		'stopVoice',
		'uploadVoice',
		'downloadVoice',
		'chooseImage',
		'previewImage',
		'uploadImage',
		'downloadImage',
		'getNetworkType',
		'openLocation',
		'getLocation',
		'hideOptionMenu',
		'showOptionMenu',
		'closeWindow',
		'scanQRCode',
		'chooseWXPay',
		'openProductSpecificView',
		'addCard',
		'chooseCard',
		'openCard'
	];
	
	wx.config(jssdkconfig);
	
</script>
EOF;
	echo $script;
}
?>